package org.mobile.makibis;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.mobile.makibis.util.ContentLoader;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class AddSpecies extends Activity {
	
	private static final int TIME_OUT = 3000;
	private String feedURL = "http://10.0.2.2:8080/MakiBIS/retrieve", newURL, recent, missing;
	private String[] tax = {"genus", "family", "order", "class", "phylum", "kingdom", "domain"};
	private TextView[] taxRankTextView = new TextView[7];
	private TextView[] dataTextView = new TextView[18];
	private TextView prevTaxText, nextTaxText, newGenus, chooseGenus, txt;
	private EditText subspeciesEditText, subgenusEditText;
	private EditText dataEditText [] = new EditText[18]; 
	@SuppressWarnings("unchecked")
	private ArrayAdapter<String>[] taxDataAdapter = new ArrayAdapter[7];
	private Spinner nextSpinner, prevSpinner;
	private Spinner[] taxSpinner = new Spinner[7]; 
	@SuppressWarnings("unchecked")
	private List<String>[] taxDataArray = new ArrayList[7];
	private List<String> recentDataArray;
	private JSONArray jsonarray;
	private JSONObject obj;
	private int p = 0, i, error, visibility;
	private Button saveBtn, nxtBtn, prevBtn;
	private ViewFlipper viewFlipper;
	private Animation animFlipInNext, animFlipOutNext, animFlipInPrevious, animFlipOutPrevious;
	private DatePicker dp; 
	private JSONObject object;
	private int dateID, encoderID, basisID, threatID, vernacularID, charID, sexID, refID, locID, countryID, continentID, distID, genusID;
	public int speciesID;
	ContentLoader cont = new ContentLoader();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addspecies);
     
    	initializeComponents();
        setContent(feedURL + "/genus");  
    }
    
    private class buttonListener implements OnClickListener{ //save Button
    	@Override
    	public void onClick(View v) {
    		try{
    			String makibisURL = getResources().getString(R.string.feed_url);
    			String foreignKeyID="";
    			if(saveBtn.isPressed()){
	    			if(completeInput()){ 
	    				
	    				if(visibility==0){ //genus spinner is shown
	    					for(i=0; i<jsonarray.length()-1; i++) 
	    			    	    if(recent.matches(jsonarray.getJSONObject(i).getString("name"))) genusID = Integer.parseInt(jsonarray.getJSONObject(i).getString("foreignKeyID").toString());
	    				}
	    				else{ //genus spinner not shown
	    					for(i=0; i<jsonarray.length()-1; i++) 
	    			    	    if(recent.matches(jsonarray.getJSONObject(i).getString("name"))) foreignKeyID = jsonarray.getJSONObject(i).getString("ID").toString();
	    			    	    	
	    					object = new JSONObject(); //for Genus
	    					object.put("function", "create");
	    					object.put("name", dataEditText[1].getText().toString());
	    					object.put("foreignKeyID", foreignKeyID);
	    					object.put("subGenus", subgenusEditText.getText().toString());
	    					genusID = setData("http://10.0.2.2:8080/MakiBIS/create/genus",object);
	    			    }
	    				updateDatabase();
	    				
	    				
	    			}
	    			else{ 
		    			final AlertDialog alert1 =  new AlertDialog.Builder(AddSpecies.this).create();
		    			alert1.setTitle("Missing!");
		    			alert1.setMessage(missing.toString());
		    			alert1.setButton("OK", new DialogInterface.OnClickListener() {
		    				
		    				@Override
		    				public void onClick(DialogInterface arg0, int arg1) {
		    					alert1.cancel();
		    				}
		    			});
		    			alert1.show();
	    			}
    			}
    			else if(nxtBtn.isPressed()){
    				viewFlipper.setInAnimation(animFlipInNext);
                    viewFlipper.setOutAnimation(animFlipOutNext);
                    viewFlipper.showNext();
    			}
    			else if(prevBtn.isPressed()){
    				viewFlipper.setInAnimation(animFlipInPrevious);
	                viewFlipper.setOutAnimation(animFlipOutPrevious);
	                viewFlipper.showPrevious();
    			}
    		}catch (Exception e) {
    			e.printStackTrace();
			}
    	}
    }  
    
    public void initializeComponents(){
    	p=0;
        viewFlipper = (ViewFlipper)findViewById(R.id.viewflipper);
        animFlipInNext = AnimationUtils.loadAnimation(this, R.anim.flipinnext);
        animFlipOutNext = AnimationUtils.loadAnimation(this, R.anim.flipoutnext);
        animFlipInPrevious = AnimationUtils.loadAnimation(this, R.anim.flipinprevious);
        animFlipOutPrevious = AnimationUtils.loadAnimation(this, R.anim.flipoutprevious);
                
        taxRankTextView[0] = (TextView)findViewById(R.id.genusTextView);
        taxRankTextView[1] = (TextView)findViewById(R.id.familyTextView);
        taxRankTextView[2] = (TextView)findViewById(R.id.orderTextView);
        taxRankTextView[3] = (TextView)findViewById(R.id.classTextView);
        taxRankTextView[4] = (TextView)findViewById(R.id.phylumTextView);
        taxRankTextView[5] = (TextView)findViewById(R.id.kingdomTextView);
        taxRankTextView[6] = (TextView)findViewById(R.id.domainTextView);
        newGenus = (TextView)findViewById(R.id.genusNew);
        chooseGenus = (TextView)findViewById(R.id.genusChoose);
       
        taxSpinner[0] = (Spinner)findViewById(R.id.genusSpinner);
        taxSpinner[1] = (Spinner)findViewById(R.id.familySpinner);
        taxSpinner[2] = (Spinner)findViewById(R.id.orderSpinner);
        taxSpinner[3] = (Spinner)findViewById(R.id.classSpinner);
        taxSpinner[4] = (Spinner)findViewById(R.id.phylumSpinner);
        taxSpinner[5] = (Spinner)findViewById(R.id.kingdomSpinner);
        taxSpinner[6] = (Spinner)findViewById(R.id.domainSpinner);
        
        dataTextView[0] = (TextView)findViewById(R.id.speciesTextView);
        dataTextView[1] = (TextView)findViewById(R.id.genusTextView);
        dataTextView[2] = (TextView)findViewById(R.id.charTextView);
        dataTextView[3] = (TextView)findViewById(R.id.vernacularTextView);
        dataTextView[4] = (TextView)findViewById(R.id.sexTextView);
        dataTextView[5] = (TextView)findViewById(R.id.referenceTextView);
        dataTextView[6] = (TextView)findViewById(R.id.longitudeTextView);
        dataTextView[7] = (TextView)findViewById(R.id.latitudeTextView);
        dataTextView[8] = (TextView)findViewById(R.id.countryTextView);
        dataTextView[9] = (TextView)findViewById(R.id.continentTextView);
        dataTextView[10] = (TextView)findViewById(R.id.distTextView);
        dataTextView[11] = (TextView)findViewById(R.id.threatTextView);
        dataTextView[12] = (TextView)findViewById(R.id.basisTextView);
        dataTextView[13] = (TextView)findViewById(R.id.fnameTextView);
        dataTextView[14] = (TextView)findViewById(R.id.mnameTextView);
        dataTextView[15] = (TextView)findViewById(R.id.lnameTextView);
        
        subspeciesEditText = (EditText)findViewById(R.id.subSpeciesEditText);
        subgenusEditText = (EditText)findViewById(R.id.subGenusEditText);
        dataEditText[0] = (EditText)findViewById(R.id.speciesEditText);
        dataEditText[1] = (EditText)findViewById(R.id.genusEditText);
        dataEditText[2] = (EditText)findViewById(R.id.charEditText);
        dataEditText[3] = (EditText)findViewById(R.id.vernacularEditText);
        dataEditText[4] = (EditText)findViewById(R.id.sexEditText);
        dataEditText[5] = (EditText)findViewById(R.id.referenceEditText);
        dataEditText[6] = (EditText)findViewById(R.id.longitudeEditText);
        dataEditText[7] = (EditText)findViewById(R.id.latitudeEditText);
        dataEditText[8] = (EditText)findViewById(R.id.countryEditText);
        dataEditText[9] = (EditText)findViewById(R.id.continentEditText);
        dataEditText[10] = (EditText)findViewById(R.id.distEditText);
        dataEditText[11] = (EditText)findViewById(R.id.threatEditText);
        dataEditText[12] = (EditText)findViewById(R.id.basisEditText);
        dataEditText[13] = (EditText)findViewById(R.id.fnameEditText);
        dataEditText[14] = (EditText)findViewById(R.id.mnameEditText);
        dataEditText[15] = (EditText)findViewById(R.id.lnameEditText);
        
       
        for(i=0; i<tax.length; i++) taxDataArray[i] = new ArrayList<String>();
        
        newGenus.setOnClickListener(new genusListener());
        chooseGenus.setOnClickListener(new genusListener());
        saveBtn = (Button) findViewById(R.id.btnSave);
        nxtBtn = (Button) findViewById(R.id.btnNext);
        prevBtn = (Button) findViewById(R.id.btnPrev);
        saveBtn.setOnClickListener(new buttonListener());
        nxtBtn.setOnClickListener(new buttonListener());
        prevBtn.setOnClickListener(new buttonListener());
        
        dp=(DatePicker)findViewById(R.id.datePick);
    	
    }
    
    private void updateDatabase(){
    	//other tables to be updated..
		try{
    	
		object = new JSONObject(); //for characteristics
		object.put("function", "create");
		object.put("name", dataEditText[2].getText().toString());
		charID = setData("http://10.0.2.2:8080/MakiBIS/create/characteristic", object);
		
		object = new JSONObject(); //for vernacular name
		object.put("function", "create");
		object.put("name", dataEditText[3].getText().toString());
		vernacularID = setData("http://10.0.2.2:8080/MakiBIS/create/vernacularname", object);
		
		object = new JSONObject(); //for sex
		object.put("function", "create");
		object.put("name", dataEditText[4].getText().toString());
		sexID = setData("http://10.0.2.2:8080/MakiBIS/create/sex", object);
		
		object = new JSONObject(); //for reference
		object.put("function", "create");
		object.put("name", dataEditText[5].getText().toString());
		refID = setData("http://10.0.2.2:8080/MakiBIS/create/reference", object);
		
		object = new JSONObject(); //for location
		object.put("function", "create");
		object.put("longitude", dataEditText[6].getText().toString());
		object.put("latitude", dataEditText[7].getText().toString());
		locID = setData("http://10.0.2.2:8080/MakiBIS/create/location", object);
		
		object = new JSONObject(); //for country
		object.put("function", "create");
		object.put("name", dataEditText[8].getText().toString());
		countryID = setData("http://10.0.2.2:8080/MakiBIS/create/country", object);
		
		object = new JSONObject(); //for continent
		object.put("function", "create");
		object.put("name", dataEditText[9].getText().toString());
		continentID = setData("http://10.0.2.2:8080/MakiBIS/create/continent", object);
		
		object = new JSONObject(); //for distribution
		object.put("function", "create");
		object.put("name", dataEditText[10].getText().toString());
		distID = setData("http://10.0.2.2:8080/MakiBIS/create/distribution", object);
		
		object = new JSONObject(); //for threat status
		object.put("function", "create");
		object.put("name", dataEditText[11].getText().toString());
		threatID = setData("http://10.0.2.2:8080/MakiBIS/create/threatstatus", object);
		
		object = new JSONObject(); //for basis of record
		object.put("function", "create");
		object.put("name", dataEditText[12].getText().toString());
		basisID = setData("http://10.0.2.2:8080/MakiBIS/create/basisofrecord", object);
		
		object = new JSONObject(); //for encoderinformation
		object.put("function", "create");
		object.put("firstname", dataEditText[13].getText().toString());
		object.put("middlename", dataEditText[14].getText().toString());
		object.put("lastname", dataEditText[15].getText().toString());
		encoderID = setData("http://10.0.2.2:8080/MakiBIS/create/encoderinformation", object); 
		
		object = new JSONObject(); //for date modified
		object.put("function", "create");
		object.put("day", dp.getDayOfMonth());
		object.put("month", dp.getMonth() + 1);
		object.put("year", dp.getYear());
		dateID = setData("http://10.0.2.2:8080/MakiBIS/create/datemodified", object);
		
		object = new JSONObject(); //for species
		object.put("function", "create");
		object.put("name", dataEditText[0].getText().toString());
		object.put("foreignKeyID", genusID);
		object.put("basisOfRecordID", basisID);
		object.put("characteristicID", charID);
		object.put("continentID", continentID);
		object.put("countryID", countryID);
		object.put("dateModifiedID", dateID);
		object.put("distributionID", distID);
		object.put("encoderInformationID", encoderID);
		object.put("locationID", locID);
		object.put("referenceID", refID);
		object.put("sexID", sexID);
		object.put("threatStatusID", threatID);
		object.put("vernacularNameID", vernacularID);
		object.put("subSpecies", dataEditText[0].getText().toString());
		speciesID = setData("http://10.0.2.2:8080/MakiBIS/create/species", object);
		
		}catch (Exception e) {
			e.printStackTrace();
		}
    	
    }
    
    private int setData(String URL, JSONObject object){ //client test application-POST
    	int ID = 0;
    	try{
	    	Representation rep = new JsonRepresentation(object);
			rep.setMediaType(MediaType.APPLICATION_JSON);
			ClientResource requestResource = new ClientResource(URL);
		    Representation reply = requestResource.post(rep);
		    String newID = reply.getText();
		    JSONObject jsObj = new JSONObject(newID);
		    ID = Integer.parseInt(jsObj.getString("ID").toString());
    	}catch (Exception e) {
    		e.printStackTrace();
		}
    	
    	return ID;
    }
  
    private class genusListener implements OnClickListener{
    	@Override
		public void onClick(View v) {
    		if(newGenus.isShown()){
    			visibility=8;
    			taxSpinner[p].setVisibility(View.GONE);
    			chooseGenus.setVisibility(View.VISIBLE);
    			newGenus.setVisibility(View.GONE);
    			dataEditText[1].setVisibility(View.VISIBLE);
    			newURL = feedURL + "/" + tax[++p];	    		
	    		setContent(newURL);
	    		createSpinner();
		    	taxSpinner[p].setVisibility(View.VISIBLE);
		    	taxRankTextView[p].setVisibility(View.VISIBLE);
		    	--p;
    		}
    		else if(chooseGenus.isShown()){
    			taxSpinner[p].setVisibility(View.VISIBLE);
    			chooseGenus.setVisibility(View.GONE);
    			newGenus.setVisibility(View.VISIBLE);
    			dataEditText[1].setVisibility(View.GONE);
    			taxSpinner[p+1].setVisibility(View.GONE);
		    	taxRankTextView[p+1].setVisibility(View.GONE);
    		}
		}
    } 
    
    public Boolean completeInput(){ //checks if input is complete
    	error=0;
    	try{
	    	missing = "The following field/s is/are required: " + "\n";
	    	for(i=0; i<dataEditText.length; i++){
	    		if(dataEditText[i].getText().toString().trim().length()==0){
	    			
	    			visibility = taxSpinner[0].getVisibility();
	    			if(i==1 && visibility==0) {Log.d("DEBUG", "NO " + i);} // genus spinner is shown
	    			else{
	    				error++;
	    				missing = missing + dataTextView[i].getText().toString() + "\n"; 
	    			}
	    		}
	    	}
    	}catch (Exception e) {
    		e.printStackTrace();
		}
    	if(error>0) return false;
    	return true;
    }
    
    public void setContent(String feedURL){ //GET
    	try{
    		recentDataArray = new ArrayList<String>(); 
	        JSONObject content = new org.json.JSONObject(cont.loadJSON(feedURL));
			jsonarray = content.getJSONArray("data");
	   	
			for(i=0; i<jsonarray.length(); i++) {			
				obj = jsonarray.getJSONObject(i);
				recentDataArray.add(obj.getString("name"));
			}
			
			for(i=0; i<tax.length; i++){
				if(tax[i].matches(tax[p]))
					taxDataArray[p] = recentDataArray;
			}
			createSpinner();
			
        } catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    public void createSpinner(){
    	try{
    		
    		for(i=0; i<tax.length; i++){
    			if(tax[i].matches(tax[p])){
    				taxDataAdapter[p] = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, taxDataArray[p]){
    					public boolean isEnabled(int position) {
    		                if(position == 0){
    		                    return false; 
    		                }else{
    		                    return true;
    		                }
    		              } 
    		              public boolean areAllItemsEnabled() { 
    		                return false; 
    		              } 
    				};
    				taxDataAdapter[p].setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    				taxDataAdapter[p].notifyDataSetChanged();
    				taxSpinner[p].setAdapter(taxDataAdapter[p]);	
    				taxSpinner[p].setOnItemSelectedListener(new MyOnItemSelectedListener());
    				taxDataAdapter[p].notifyDataSetChanged();
    			}	
    		}
    	}catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	      try{
		      recent = parent.getItemAtPosition(pos).toString();
	    	  if(recent.matches("Unknown")){
	    		 newURL = feedURL + "/" + tax[++p];
	    		 setContent(newURL);
	    		 createSpinner();
	    		 for(i=0; i<tax.length; i++){
	    			 if(tax[i].matches(tax[p])){
	    				 nextTaxText = taxRankTextView[p];
	    				 nextSpinner = taxSpinner[p];
	    				 prevTaxText = taxRankTextView[p-1];
	    				 prevSpinner = taxSpinner[p-1];
	    			 }
	    		 }
	    		 nextTaxText.setVisibility(View.VISIBLE);
	    		 nextSpinner.setVisibility(View.VISIBLE);
	    		 prevTaxText.setVisibility(View.GONE);
	    		 prevSpinner.setVisibility(View.GONE); 
	    	 }
	      }catch (Exception e) {
			e.printStackTrace();
		  } 
	     
	    }

	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}  
}